﻿/*
Copyright (c) 2013, Bartłomiej Gałkowski
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: 

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer. 
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Linq;

namespace PyroGen
{
    public class CommandLineArguments
    {
        private readonly Dictionary<String, String> _arguments;

        public CommandLineArguments()
        {
            _arguments = new Dictionary<string, string>();
        }

        public CommandLineArguments(Dictionary<String, String> args)
        {
            _arguments = args;
        }

        public bool OptionExists(string option)
        {
            return _arguments.ContainsKey(option.ToLower());
        }

        public bool OptionExists(string opt1, string opt2)
        {
            return OptionExists(opt1) || OptionExists(opt2);
        }

        public string GetOptionValue(string option)
        {
            if (!OptionExists(option))
                return null;

            return _arguments[option.ToLower()];
        }

        public string GetOptionValue(string opt1, string opt2)
        {
            if (OptionExists(opt1))
                return GetOptionValue(opt1);

            if (OptionExists(opt2))
                return GetOptionValue(opt2);

            return null;
        }

        private static int NumberOfQuotes(String str)
        {
            return str.Count(f => f == '"');
        }


        public static List<String> ConcatQuotedArguments(String[] args)
        {
            var input = new List<String>(args);

            var arguments = new List<String>();

            // loop for preventing overflow
            for (var i = 0; i < 20; i++)
            {
                // if input empty end loop
                if (input.Count == 0)
                    break;

                List<String> elems;

                elems = input.TakeWhile(elem => NumberOfQuotes(elem) == 0).ToList();
                input = input.SkipWhile(elem => NumberOfQuotes(elem) == 0).ToList();

                if (elems.Count > 0)
                    arguments = arguments.Concat(elems).ToList();

                // Take the element with quotes
                if (input.Count > 0)
                {
                    arguments.Add(input[0]);
                    input = input.Skip(1).ToList();
                }

                // Take elements without quotes
                elems = input.TakeWhile(elem => NumberOfQuotes(elem) == 0).ToList();
                input = input.SkipWhile(elem => NumberOfQuotes(elem) == 0).ToList();

                if (elems.Count > 0)
                    arguments.Add(elems.Aggregate((workingSentence, next) => workingSentence + " " + next));

                // Take the elemen with quotes
                if (input.Count > 0)
                {
                    arguments[arguments.Count - 1] += " " + input[0];
                    input = input.Skip(1).ToList();
                }
            }

            return arguments;
        }

        public static String StripQuotes(String s)
        {
            s = s.TrimStart('"');
            s = s.TrimEnd('"');
            return s;
        }


        public static CommandLineArguments Parse(string[] args)
        {
            List<String> arguments = ConcatQuotedArguments(args);

            var argParams = new Dictionary<String, String>();

            foreach (String arg in arguments)
            {
                String[] argArray;

                argArray = arg.TrimStart("-/".ToCharArray()).Split(":=".ToCharArray(), 2);

                String value, key = argArray[0].ToLower();

                if ((argArray.Length > 1) && (argArray[1].Length > 0))
                    value = StripQuotes(argArray[1]);
                else
                    value = null;

                argParams.Add(key, value);
            }

            return new CommandLineArguments(argParams);
        }
    }
}